<template>
  <div>
    <div class="userSearch">
      <el-form :inline="true" :model="searchForm" class="demo-form-inline">
        <el-form-item label="姓名">
          <el-input
            v-model="searchForm.query.name"
            placeholder="请输入姓名"
          ></el-input>
        </el-form-item>
        <el-form-item label="电话号码">
          <el-input
            v-model="searchForm.query.phone"
            placeholder="请输入电话号码"
          ></el-input>
        </el-form-item>
        <el-form-item label="专业名称">
          <el-select
            v-model="searchForm.query.major_id"
            placeholder="请选择专业名称"
          >
            <el-option
              v-for="item in majorNameArr"
              :key="item.major_id"
              :label="item.name"
              :value="item.major_id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="onSubmit">查询</el-button>
          <el-button @click="onReset">重置</el-button>
          <el-button type="success" @click="onAddForm">添加</el-button>
        </el-form-item>
      </el-form>
    </div>
    <div class="userTable">
      <el-table :data="tableData" style="width: 100%" border stripe>
        <el-table-column label="姓名" align="center">
          <template slot-scope="scope">
            <span>{{ scope.row.name }}</span>
          </template>
        </el-table-column>
        <el-table-column label="年龄" align="center">
          <template slot-scope="scope">
            <span>{{ scope.row.age }}</span>
          </template>
        </el-table-column>
        <el-table-column label="性别" align="center">
          <template slot-scope="scope">
            <span>{{ scope.row.sex == 0 ? "男" : "女" }}</span>
          </template>
        </el-table-column>
        <el-table-column label="专业" align="center">
          <template slot-scope="scope">
            <span>{{ majorName({ ...scope.row }) }}</span>
          </template>
        </el-table-column>
        <el-table-column label="电话" align="center">
          <template slot-scope="scope">
            <span>{{ scope.row.phone }}</span>
          </template>
        </el-table-column>
        <el-table-column label="爱好" align="center">
          <template slot-scope="scope">
            <div slot="reference" class="name-wrapper">
              <el-tag
                size="medium"
                v-for="item in hobbyArr({ ...scope.row })"
                :key="item"
                style="margin-right: 5px"
                >{{ item }}</el-tag
              >
            </div>
          </template>
        </el-table-column>
        <el-table-column label="创建时间" align="center">
          <template slot-scope="scope">
            <span>{{ scope.row.created_at }}</span>
          </template>
        </el-table-column>
        <el-table-column label="更新时间" align="center">
          <template slot-scope="scope">
            <span>{{ scope.row.updated_at }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-button size="mini" @click="handleEdit(scope.$index, scope.row)"
              >编辑</el-button
            >
            <el-button
              type="danger"
              @click="handleDelete(scope.$index, scope.row)"
              size="mini"
              slot="reference"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div class="block">
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="searchForm.offset"
        :page-sizes="[5, 10, 15, 20]"
        :page-size="searchForm.limit"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      ></el-pagination>
    </div>
    <!-- 表单 -->
    <el-dialog :title="dialogTitle" :visible.sync="dialogFormVisible">
      <el-form :model="editform" ref="editform">
        <el-form-item
          label="姓名"
          prop="name"
          :label-width="formLabelWidth"
          :rules="[{ required: true, message: '姓名不能为空' }]"
        >
          <el-input
            v-model="editform.name"
            autocomplete="off"
            style="width: 300px"
          ></el-input>
        </el-form-item>
        <el-form-item label="专业" :label-width="formLabelWidth">
          <el-select v-model="editform.major_id" placeholder="请专业名称">
            <el-option
              v-for="item in majorNameArr"
              :key="item.major_id+'-only'"
              :label="item.name"
              :value="item.major_id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="年龄" :label-width="formLabelWidth">
          <el-input
            v-model.number="editform.age"
            autocomplete="off"
            style="width: 300px"
          ></el-input>
        </el-form-item>
        <el-form-item label="电话号码" :label-width="formLabelWidth">
          <el-input
            v-model="editform.phone"
            autocomplete="off"
            style="width: 300px"
          ></el-input>
        </el-form-item>
        <el-form-item
          label="性别"
          prop="resource"
          :label-width="formLabelWidth"
        >
          <el-radio-group v-model="editform.sex">
            <el-radio :label="0">男</el-radio>
            <el-radio :label="1">女</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item
          label="爱好"
          :label-width="formLabelWidth"
          prop="hobby"
          :rules="[{ required: true, message: '爱好不能为空' }]"
        >
          <el-tag
            v-for="tag in hobbyTag"
            :key="tag"
            closable
            :disable-transitions="false"
            @close="handleClose(tag)"
            >{{ tag }}</el-tag
          >
          <el-input
            class="input-new-tag"
            v-if="inputVisible"
            v-model="inputValue"
            ref="saveTagInput"
            size="small"
            @keyup.enter.native="handleInputConfirm"
            @blur="handleInputConfirm"
          ></el-input>
          <el-button
            v-else
            class="button-new-tag"
            size="small"
            @click="showInput"
            >+ New Tag</el-button
          >
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="dialogClick('editform')"
          >确 定</el-button
        >
      </div>
    </el-dialog>
  </div>
</template>
<script>
import {
  getMajorName,
  getUserInfo,
  editUserInfo,
  addUserInfo,
  delUserInfo
} from '../api/User'

export default {
  name: 'User',
  // created () {
  //     // 这行代码的意思是定义一个全局变量，等于该组件的实例
  //    window.myData = this
  // },
  data () {
    return {
      searchForm: {
        limit: 5,
        offset: 1,
        query: {
          name: '',
          phone: '',
          major_id: ''
        }
      },
      editform: {
        name: '',
        phone: '',
        age: '',
        sex: 0,
        major_id: '',
        hobby: ''
      },
      tableData: [],
      majorNameArr: [],
      dialogTitle: '',
      dialogFormVisible: false,
      formLabelWidth: '80px',
      // tag
      inputVisible: false,
      inputValue: '',
      total: 0
    }
  },
  watch: {
    majorNameArr: {
      handler (newValue, oldValue) {
        console.log(newValue)
      }
    }
  },
  created () {
    this.getList()
    // console.log(this.majorNameArr)
    getMajorName().then((res) => {
      // console.log(res.data.data);
      this.majorNameArr = res.data.data
    })
  },
  methods: {
    // 查询接口
    getList () {
      getUserInfo(this.searchForm).then((res) => {
        // console.log(res.data.data.rows);
        this.tableData = res.data.data.rows
        this.total = res.data.data.count
      })
    },
    onSubmit () {
      this.getList()
    },
    onAddForm () {
      this.dialogFormVisible = true
      this.dialogTitle = '添加'
      this.editform = {
        name: '',
        phone: '',
        age: '',
        sex: 0,
        major_id: '',
        hobby: ''
      }
    },
    onReset () {
      this.searchForm = {
        limit: 5,
        offset: 1,
        query: {
          name: '',
          phone: '',
          major_id: ''
        }
      }
      this.getList()
    },
    // 编辑
    handleEdit (index, row) {
      console.log(index, row)
      this.dialogFormVisible = true
      this.editform = { ...row }
    },
    //   删除
    handleDelete (index, row) {
      // console.log(index, row);
      this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          delUserInfo({ id: row.id }).then((res) => {
            console.log(res.data)
            this.$message({
              type: 'success',
              message: '删除成功!'
            })
            this.getList()
          })
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
    },
    // tag
    handleClose (tag) {
      this.hobbyTag.splice(this.hobbyTag.indexOf(tag), 1)
      console.log(123)
    },

    showInput () {
      this.inputVisible = true
      this.$nextTick(() => {
        this.$refs.saveTagInput.$refs.input.focus()
      })
    },

    handleInputConfirm () {
      let inputValue = this.inputValue
      if (inputValue) {
        this.hobbyTag.push(inputValue)
        console.log(333, this.hobbyTag)
        this.editform.hobby = this.hobbyTag.join(',')
      }
      this.inputVisible = false
      this.inputValue = ''
    },
    // 表单确定
    dialogClick (formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
        } else {
          console.log('error submit!!')
          return false
        }
      })
      if (this.editform.id) {
        editUserInfo(this.editform).then((res) => {
          console.log(res.data)
          if (res.data.success === true) {
            this.$message({
              message: res.data.data.msg,
              type: 'success'
            })
            this.dialogFormVisible = false
            this.getList()
          }
        })
      } else {
        // 添加
        addUserInfo(this.editform).then((res) => {
          console.log(res.data)
          if (res.data.success === true) {
            this.$message({
              message: res.data.data.msg,
              type: 'success'
            })
            this.dialogFormVisible = false
            this.getList()
          }
        })
      }
    },
    // 分页
    handleSizeChange (val) {
      this.searchForm.limit = val
      this.getList()
    },
    handleCurrentChange (val) {
      this.searchForm.offset = val
      this.getList()
    }
  },

  computed: {
    hobbyArr () {
      return function (row) {
        return row.hobby.split(',')
      }
    },
    majorName () {
      return function (row) {
        const nameArr = this.majorNameArr.filter(
          (item) => row.major_id === item.major_id
        )
        return nameArr.length > 0 ? nameArr[0].name : ''
      }
    },
    hobbyTag () {
      return this.editform.hobby === '' ? [] : this.editform.hobby.split(',')
    }
  }
}
</script>
<style scoped>
.userSearch {
  margin-top: 50px;
  margin-left: 30px;
}
.el-tag + .el-tag {
  margin-left: 10px;
}
.button-new-tag {
  margin-left: 10px;
  height: 32px;
  line-height: 30px;
  padding-top: 0;
  padding-bottom: 0;
}
.input-new-tag {
  width: 90px;
  margin-left: 10px;
  vertical-align: bottom;
}
</style>
